package ooo.reindeer.concurrent.coder;

import ooo.reindeer.concurrent.ICoder;

import java.io.*;

public class ObjectCoder<T extends Serializable> implements ICoder<T, byte[]> {
    @Override
    public T decode(byte[] bytes) {
        T obj = null;

        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bis);
            obj = (T) ois.readObject();
            ois.close();
            bis.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return obj;
    }

    @Override
    public byte[] encode(T a) {
        byte[] bytes;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(a);
            oos.flush();
            bytes = bos.toByteArray();
            oos.close();
            bos.close();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
        return bytes;
    }
}
